package com.ui.zhong.webview.webviewproc

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import com.ui.zhong.webview.ACallback
import com.ui.zhong.webview.AWebViewProcToMain
import com.ui.zhong.webview.mainproc.MainProcCommandService
import com.walt.zhong.base.BaseApplication

class WebViewProcCmdDispatcher:ServiceConnection{
    private val TAG = "WebViewProcCmdDispatcher"
    private var aWebViewProcToMain:AWebViewProcToMain?=null
    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        Log.d(TAG,"onServiceConnected: $name")
        aWebViewProcToMain =
            AWebViewProcToMain.Stub.asInterface(service)
        // 断开重连
        initAIDLConnection()
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        Log.d(TAG,"onServiceDisconnected: $name")
        aWebViewProcToMain = null
    }

    override fun onBindingDied(name: ComponentName?) {
        super.onBindingDied(name)
        aWebViewProcToMain = null
        Log.d(TAG,"onServiceDisconnected: $name")
        // 断开重连
        initAIDLConnection()
    }

    fun initAIDLConnection(){
        val intent = Intent(BaseApplication.sApplication,MainProcCommandService::class.java)
        val bindService =
            BaseApplication.sApplication.bindService(intent, this, Context.BIND_AUTO_CREATE)
        Log.d(TAG,"initAIDLConnection: bind service result: $bindService")
    }

    companion object{
        private var sInstance:WebViewProcCmdDispatcher?= null
        fun getInstance():WebViewProcCmdDispatcher{
            if(sInstance == null){
                synchronized(WebViewProcCmdDispatcher::class.java){
                    sInstance = WebViewProcCmdDispatcher()
                }
            }

            return sInstance!!
        }
    }

    fun executeCommand(
        cmdName:String,
        params:String,
        webView:ComposeWebView
    ){
        Log.d(TAG,"executeCommand: cmdName:$cmdName , param: $params")
        aWebViewProcToMain?.run {
            handleWebViewCmd(cmdName,params,object :ACallback.Stub(){
                override fun onResult(callbackName: String?, response: String?) {
                    webView.handleCallBack(callbackName,response)
                }
            })
        }

    }
}